package com.ctakit.sdk.app;


import android.text.TextUtils;

import com.ctakit.sdk.SdkApplication;
import com.ctakit.sdk.app.util.RequestUtil;
import com.ctakit.sdk.exception.BusinessException;
import com.ctakit.sdk.http.OkHttpMethod;
import com.ctakit.sdk.http.okhttp.OkHttpUtils;
import com.ctakit.sdk.http.okhttp.builder.OkHttpRequestBuilder;
import com.ctakit.sdk.http.okhttp.builder.PostFormBuilder;
import com.ctakit.sdk.http.okhttp.builder.PostStringBuilder;
import com.ctakit.sdk.http.okhttp.callback.StringCallback;
import com.ctakit.sdk.http.okhttp.request.RequestCall;
import com.ctakit.sdk.util.JsonUtils;

import java.io.File;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.MediaType;

/**
 * Created by lizhenmin on 15/8/28.
 */
public final class MyHttpUtils {

    /**
     * 请求方式
     **/



    //
    private static OkHttpRequestBuilder builderRequestBuilder(OkHttpMethod httpMethod, String url) {
        OkHttpRequestBuilder okHttpRequestBuilder;
        switch (httpMethod) {
            case GET:
                okHttpRequestBuilder = OkHttpUtils.get().url(url);
                break;
            case POST:
                okHttpRequestBuilder = OkHttpUtils.post().url(url);
                break;
            case POST_BODY:
                okHttpRequestBuilder = OkHttpUtils.postString().url(url);
                break;
            case PUT:
                okHttpRequestBuilder = OkHttpUtils.put().url(url);
                break;

            default:
                okHttpRequestBuilder = OkHttpUtils.get().url(url);
                break;
        }
        okHttpRequestBuilder.headers(((BaseApplication)SdkApplication.app()).getGlobalHeaders(false));
        return okHttpRequestBuilder;
    }


    /**
     * Get方式提交,URL中包含查询参数, 格式：http://www.g.cn?search=p&name=s.....
     *
     * @param url 提交地址
     * @return 响应消息
     * @throws BusinessException
     */
    public static void get(String url, StringCallback stringCallback) {

        doExecute(builderRequestBuilder(OkHttpMethod.GET, url), stringCallback);

    }

    /**
     * Get方式提交,URL中不包含查询参数, 格式：http://www.g.cn
     *
     * @param url    提交地址
     * @param params 查询参数集, 键/值对
     * @return 响应消息
     * @throws BusinessException
     */
    public static void get(String url, Map<String, String> params, StringCallback stringCallback) {
        StringBuffer strtTotalURL = new StringBuffer(url);

        if (strtTotalURL.indexOf("?") == -1) {
            strtTotalURL.append("?").append(RequestUtil.getUrl(params));
        } else {
            strtTotalURL.append("&").append(RequestUtil.getUrl(params));
        }
        get(strtTotalURL.toString(), stringCallback);
    }

    /**
     * Post方式提交,URL中不包含提交参数, 格式：http://www.g.cn
     *
     * @param url    提交地址
     * @param params 提交参数集, 键/值对
     * @return 响应消息
     */
    public static void post(String url, Map<String, String> params, StringCallback stringCallback) {
        post(url, params, false, stringCallback);
    }

    public static void put(String url, Map<String, String> params, StringCallback stringCallback) {
        put(url, params, false, stringCallback);
    }


    /**
     * Post方式提交,URL中不包含提交参数, 格式：http://www.g.cn
     *
     * @param url    提交地址
     * @param params 提交参数集, 键/值对
     * @return 响应消息
     */
    public static void post(String url, Map<String, String> params, boolean multipartData, StringCallback stringCallback) {

        if (multipartData) {
            PostFormBuilder builder = (PostFormBuilder) builderRequestBuilder(OkHttpMethod.POST, url);
            Map<String, String> formParams = new TreeMap<>();

            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> map : params.entrySet()) {
                    String[] key = map.getKey().split("\\.");
                    String[] uploadKey = new String[2];
                    String value = map.getValue();
                    if (key.length == 1) {
                        uploadKey[1] = "String";
                        uploadKey[0] = key[0];
                    } else {
                        uploadKey = key;
                    }
                    if (uploadKey[1].equals("String")) {
                        formParams.put(uploadKey[0], value);
                    } else if (uploadKey[1].equals("File")) {

                        if(!TextUtils.isEmpty(value)){
                            String[] filePaths = value.split(";");
                            for (String path:filePaths){
                                File dataFile = new File(path);
                                if (dataFile.exists() && dataFile.isFile()) {
                                    builder.addFile(uploadKey[0], dataFile.getName(), dataFile);
                                }
                            }
                        }

                    }
                }
            }
            doExecute(builder.params(formParams), stringCallback);
        } else {
            doExecute(builderRequestBuilder(OkHttpMethod.POST, url).params(params), stringCallback);
        }
    }

    public static void put(String url, Map<String, String> params, boolean multipartData, StringCallback stringCallback) {

        if (multipartData) {
            PostFormBuilder builder = (PostFormBuilder) builderRequestBuilder(OkHttpMethod.PUT, url);
            Map<String, String> formParams = new TreeMap<>();

            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> map : params.entrySet()) {
                    String[] key = map.getKey().split("\\.");
                    String[] uploadKey = new String[2];
                    String value = map.getValue();
                    if (key.length == 1) {
                        uploadKey[1] = "String";
                        uploadKey[0] = key[0];
                    } else {
                        uploadKey = key;
                    }
                    if (uploadKey[1].equals("String")) {
                        formParams.put(uploadKey[0], value);
                    } else if (uploadKey[1].equals("File")) {

                        if(!TextUtils.isEmpty(value)){
                            String[] filePaths = value.split(";");
                            for (String path:filePaths){
                                File dataFile = new File(path);
                                if (dataFile.exists() && dataFile.isFile()) {
                                    builder.addFile(uploadKey[0], dataFile.getName(), dataFile);
                                }
                            }
                        }

                    }
                }
            }
            doExecute(builder.params(formParams), stringCallback);
        } else {
            doExecute(builderRequestBuilder(OkHttpMethod.PUT, url).params(params), stringCallback);
        }
    }

    private static void postBody(String url, Map<String, String> params, StringCallback stringCallback) {

        doExecute(((PostStringBuilder) builderRequestBuilder(OkHttpMethod.POST_BODY, url)).content(JsonUtils.toJson(params)).mediaType(MediaType.parse("application/json; charset=utf-8")), stringCallback);

    }


    /**
     * Post方式提交,URL中不包含提交参数, 格式：http://www.g.cn
     *
     * @param url    提交地址
     * @param params 提交参数集, 键/值对
     * @return 响应消息
     */
    public static void multipartPost(String url, Map<String, String> params, StringCallback stringCallback) {
        post(url, params, true, stringCallback);
    }

    /**
     * get方式提交，解决SSL双向数字证书认证
     *
     * @param url     提交地址
     * @param jsonBody 提交的数据
     * @return 响应消息
     */


    public static void postBody(String url, String jsonBody, StringCallback stringCallback) {
        doExecute(((PostStringBuilder) builderRequestBuilder(OkHttpMethod.POST_BODY, url)).content(jsonBody).mediaType(MediaType.parse("application/json; charset=utf-8")), stringCallback);
    }

    public static void doExecute(OkHttpRequestBuilder requestBuilder, StringCallback stringCallback) {
        if(stringCallback.isCanCancel()){
            requestBuilder.tag(stringCallback.getTag());
        }
        RequestCall requestCall = requestBuilder.build();
        requestCall.execute(stringCallback);
    }




}

